package org.jeecg.modules.sggg.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.sggg.entity.SgDevice;
import org.jeecg.modules.sggg.entity.SgFollowUp;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.entity.SgSendMedicine;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.sggg.service.ISgSendMedicineService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.controller.SysRoleController;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 送药表
 * @Author: jeecg-boot
 * @Date: 2023-03-16
 * @Version: V1.0
 */
@Api(tags = "送药表")
@RestController
@RequestMapping("/sggg/sgSendMedicine")
@Slf4j
public class SgSendMedicineController extends JeecgController<SgSendMedicine, ISgSendMedicineService> {
    @Autowired
    private ISgSendMedicineService sgSendMedicineService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartController;

    /**
     * 分页列表查询
     *
     * @param sgSendMedicine
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "送药表-分页列表查询")
    @ApiOperation(value = "送药表-分页列表查询", notes = "送药表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgSendMedicine>> queryPageList(SgSendMedicine sgSendMedicine,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       Integer isSend, HttpServletRequest req) {
        Page<SgSendMedicine> page = new Page<>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<SysRole> roleList = sysRoleService.getUserRole(sysUser.getId());
        String code = "";
        StringBuilder sb = new StringBuilder();
        for (SysRole role : roleList) {
            sb.append(role.getRoleCode());
            sb.append(",");
        }
        String sbstr = sb.toString();
        if (sbstr.contains("admin")) {
            code = "admin";
        } else if (sbstr.contains("dept_manage")) {
            //机构管理员
            code = "dept_manage";
        } else {
            code = "other";
        }

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        if(sysDepart !=null && sysDepart.getDeptAttr()!=null){
            // 1.三高之家
            if(sysDepart.getDeptAttr().equals("1")){
//                queryWrapper.eq("doctor_id", sysUser1.getId().toString());
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if(sysDepart.getDeptAttr().equals("2")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
//                queryWrapper.in("sys_org_code", responsibleAgencies);
            }
            // 3.三高中心
            if(sysDepart.getDeptAttr().equals("3")){
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
//                sgTreatmentAssist.setResponsibleAgencies(responsibleAgencies);
            }
        }else{
            sysUser.setId(sysUser1.getId());
        }

        String regEx = "[\n`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， ·、？]";
        String name = null, sex = null, phone = null, idCard = null, threeTag = null;
        if (isSend == null) {
            isSend = 1;
        }
        if (req.getParameterMap().containsKey("name")) {
            name = Arrays.toString(req.getParameterMap().get("name")).replaceAll(regEx, "");
        }
        if (req.getParameterMap().containsKey("sex")) {
            sex = Arrays.toString(req.getParameterMap().get("sex")).replaceAll(regEx, "");
        }
        if (req.getParameterMap().containsKey("phone")) {
            phone = Arrays.toString(req.getParameterMap().get("phone")).replaceAll(regEx, "");
        }
        if (req.getParameterMap().containsKey("idCard")) {
            idCard = Arrays.toString(req.getParameterMap().get("idCard")).replaceAll(regEx, "");
        }
        if (req.getParameterMap().containsKey("threeTag")) {
            threeTag = Arrays.toString(req.getParameterMap().get("threeTag")).replaceAll(regEx, "");
        }
        IPage<SgSendMedicine> pageList = null;
        if (isSend == 1) {
            pageList = sgSendMedicineService.queryPageList(page, isSend, name, sex, phone, idCard, threeTag, sysUser.getId(), code, sysUser.getOrgCode(),responsibleAgencies);
        } else {
            pageList = sgSendMedicineService.queryList(page, isSend, name, sex, phone, idCard, threeTag, sysUser.getId(), code, sysUser.getOrgCode(),responsibleAgencies);
        }

        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param sgSendMedicine
     * @return
     */
    @AutoLog(value = "送药表-添加")
    @ApiOperation(value = "送药表-添加", notes = "送药表-添加")
    //@RequiresPermissions("org.jeecg.modules:sg_send_medicine:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgSendMedicine sgSendMedicine) {
        sgSendMedicineService.save(sgSendMedicine);
        //修改当前居民的药品是否方法的字段为0
        LambdaQueryWrapper<SgMember> sgMemberQueryWrapper = new LambdaQueryWrapper<SgMember>();
        sgMemberQueryWrapper.eq(SgMember::getId, sgSendMedicine.getMemberId());
        SgMember sgMember = sgMemberService.getOne(sgMemberQueryWrapper);
        sgMember.setSendDrug(0);
        sgMemberService.updateById(sgMember);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sgSendMedicine
     * @return
     */
    @AutoLog(value = "送药表-编辑")
    @ApiOperation(value = "送药表-编辑", notes = "送药表-编辑")
    //@RequiresPermissions("org.jeecg.modules:sg_send_medicine:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgSendMedicine sgSendMedicine) {
        sgSendMedicineService.updateById(sgSendMedicine);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "送药表-通过id删除")
    @ApiOperation(value = "送药表-通过id删除", notes = "送药表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:sg_send_medicine:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        sgSendMedicineService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "送药表-批量删除")
    @ApiOperation(value = "送药表-批量删除", notes = "送药表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:sg_send_medicine:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sgSendMedicineService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "送药表-通过id查询")
    @ApiOperation(value = "送药表-通过id查询", notes = "送药表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgSendMedicine> queryById(@RequestParam(name = "id", required = true) String id) {
        SgSendMedicine sgSendMedicine = sgSendMedicineService.getById(id);
        if (sgSendMedicine == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgSendMedicine);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param sgSendMedicine
     */
    //@RequiresPermissions("org.jeecg.modules:sg_send_medicine:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgSendMedicine sgSendMedicine) {
        return super.exportXls(request, sgSendMedicine, SgSendMedicine.class, "送药表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("sg_send_medicine:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgSendMedicine.class);
    }


    /**
     * TODO     设备管理--查询某个居民绑定的设备信息
     *
     * @param memberId 居民id
     * @return
     * @author WangJie
     * @date 2023/3/16 15:06
     * @Exception
     */

    @ApiOperation(value = "设备管理-查询某个居民绑定的设备信息", notes = "设备管理-查询某个居民绑定的设备信息")
    @GetMapping(value = "/queryByMemberId")
    public Result<List<SgSendMedicine>> queryByMemberId(@RequestParam(name = "memberId", required = true) String memberId) {
        List<SgSendMedicine> sgDevice = sgSendMedicineService.list(new QueryWrapper<SgSendMedicine>()
                .eq("member_id", memberId).orderByDesc("create_time"));
        if (sgDevice == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgDevice);
    }

    /**
     * xl ---- 居民信息管理
     *
     * @param mid 居民id
     * @return 数据
     */
    @GetMapping(value = "/queryListByMid")
    public Result<List<SgSendMedicine>> queryListByMid(String mid) {
        return Result.OK(sgSendMedicineService.list(
                new QueryWrapper<SgSendMedicine>()
                        .eq("member_id", mid)
                        .orderByDesc("create_time")
                        .select("id", "create_time", "send_medicine", "send_basis", "send_num")
        ));
    }

    /**
     * xl ---- 居民信息管理 药品发放
     * 查询送的药品
     *
     * @return 数据
     */
    @GetMapping(value = "/queryListBysendMedicine")
    public Result<List<SgSendMedicine>> queryListBysendMedicine() {
        return Result.OK(sgSendMedicineService.list(
                new QueryWrapper<SgSendMedicine>()
                        .orderByDesc("create_time")
                        .select("distinct send_medicine")
        ));
    }
}
